#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import socket
import time
import urllib2
import json


class WeChat:
    def __init__(self):
        self.CORPID = 'ww9b4dface59aab28c'  # 企业ID，在管理后台获取
        self.CORPSECRET = 'QtHgP2u_upHDFj9iI72UpaR-A5d5szbLRzvTQxcVVNI'  # 自建应用的Secret，每个自建应用里都有单独的secret
        self.AGENTID = '1000012'  # 应用ID，在后台应用中获取
        self.TOUSER = "@all"  # 接收者用户名,多个用户用|分割
        # self.getCurrentIP()

    def getCurrentIP(self):
        self.IP = self.runCommand("/usr/sbin/ip a |grep 'ens'|grep -w inet|awk '{print $2}'|awk -F '/' '{print $1}'").strip() or self.runCommand("/usr/sbin/ip a |grep 'bond0'|grep -w inet|awk '{print $2}'|awk -F '/' '{print $1}'").strip()


    def _get_access_token(self):

        url_access_token = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (self.CORPID, self.CORPSECRET)
        req = urllib2.Request(url_access_token)
        response = urllib2.urlopen(req)
        data = json.loads(response.read())
        return data["access_token"]

    def get_access_token(self):
        """
        获取token
        :return: access_token
        """
        try:
            with open('./access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('./access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('\t'.join([str(cur_time), access_token]))
                return access_token
        else:
            cur_time = time.time()
            if 0 < cur_time - float(t) < 7260:
                return access_token
            else:
                with open('./access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('\t'.join([str(cur_time), access_token]))
                    return access_token

    def send_data(self, message):
        """
        企业微信告警
        :param message: 告警内容
        :return: errmsg
        """
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": message
                },
            "safe": "0"
            }
        send_msges = json.dumps(send_values).encode('UTF-8')
        request = urllib2.Request(send_url, send_msges)
        conn = urllib2.urlopen(request).read()
        content_json = json.loads(conn)
        return content_json["errmsg"]


    def listen(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("10.1.19.33", 9100))
        sock.listen(30)  # 监听客户端连接
        while True:
            conn, addr = sock.accept()  # 接收一个客户端连接
            print(addr)
            T = threading.Thread(target=self.send_message,args=(conn,addr,))
            T.start()

    def send_message(self,conn,addr):
        result = conn.recv(2048)
        if result:  # 从接收缓冲读消息 recv buffer
            self.send_data(result)
        conn.close()  # 关闭连接



if __name__ == '__main__':
    wx = WeChat()
    wx.listen()

